<template>
  <el-cascader
    v-model="innerValue"
    :options="groupOptions"
    :show-all-levels="false"
    placeholder="请选择课程类型"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
  import { getCourseTypeByPage } from '@/apis/courseType'

  const ENU_COURSE_TYPE_CATEGORY = {
    1: '体育类',
    2: '棋类',
    3: '文艺类',
    4: '书画类',
    99: '其他',
  }

  export default {
    props: {
      value: {
        type: [String, Number],
        default: null,
      },
    },
    data() {
      return {
        innerValue: null,
        groupOptions: [],
      }
    },
    async created() {
      this.innerValue = this.value

      const { list } = await getCourseTypeByPage()
      list.forEach((item) => {
        if (item.className) {
          const group = this.getGroupByCategory(item.classtype)

          if (group) {
            group.children.push({
              label: item.className,
              value: item.id,
            })
          } else {
            this.groupOptions.push({
              label: ENU_COURSE_TYPE_CATEGORY[item.classtype] || '未知',
              value: item.classtype,
              children: [
                {
                  label: item.className,
                  value: item.id,
                },
              ],
            })
          }
        }
      })
    },
    methods: {
      getGroupByCategory(category) {
        return this.groupOptions.find((d) => d.value === category)
      },
      handleChange() {
        this.$emit('input', this.innerValue[1])
      },
    },
  }
</script>
